package com.hack.validator;


import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 规则服务类
 * 包含添加规则、获取规则和删除规则的方法
 *
 * @author hack
 * @version 1.0
 * @date 2025/07/11
 */
@Repository
public class RuleService {
    public void addRule(ValidationRule rule) throws SQLException {
        String sql = "MERGE INTO validation_rules (param_path, param_type, rule_type, rule_config, error_msg, app_id) " +
                "KEY (param_path, rule_type, app_id) " +
                "VALUES (?, ?, ?, ?, ?, ?)";

        try (Connection conn = DBManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, rule.getParamPath());
            pstmt.setString(2, rule.getParamType());
            pstmt.setString(3, rule.getRuleType());
            pstmt.setString(4, rule.getRuleConfig());
            pstmt.setString(5, rule.getErrorMsg());
            pstmt.setString(6, rule.getAppId());

            pstmt.executeUpdate();
        }
    }

    public List<ValidationRule> getRules(String appId) throws SQLException {
        List<ValidationRule> rules = new ArrayList<>();
        String sql = "SELECT * FROM validation_rules WHERE app_id = ?";

        try (Connection conn = DBManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, appId);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                ValidationRule rule = new ValidationRule();
                rule.setId(rs.getInt("id"));
                rule.setParamPath(rs.getString("param_path"));
                rule.setParamType(rs.getString("param_type"));
                rule.setRuleType(rs.getString("rule_type"));
                rule.setRuleConfig(rs.getString("rule_config"));
                rule.setErrorMsg(rs.getString("error_msg"));
                rule.setAppId(rs.getString("app_id"));
                rules.add(rule);
            }
        }
        return rules;
    }

    public void deleteRule(int id) throws SQLException {
        String sql = "DELETE FROM validation_rules WHERE id = ?";
        try (Connection conn = DBManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }
}
